package jumpingnotes.restlet;

import javax.servlet.ServletContext;

import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.Router;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.noelios.restlet.ext.servlet.ServletContextAdapter;

public class RestletApplication extends Application
{
	private ServletContext servletContext;

	public RestletApplication()
	{
		super();
	}

	public RestletApplication(Context context)
	{
		super(context);

		if (context instanceof ServletContextAdapter)
		{
			ServletContextAdapter servletContextAdapter = (ServletContextAdapter) context;
			this.servletContext = servletContextAdapter.getServletContext();
		}
	}

	/**
	 * Creates a root Restlet that will receive all incoming calls.
	 */
	@Override
	public synchronized Restlet createRoot()
	{
		Router root = null;
		if (servletContext != null)
		{
			WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
			root = (Router) ctx.getBean("restlet.root");
		}
		else
		{
			root = new Router(getContext());
		}
		return root;
	}
}
